package com.lhhu.demo.config;

import com.alibaba.fastjson.JSON;
import com.lhhu.demo.bean.HandlersMessage;
import com.lhhu.demo.bean.Logs;
import com.lhhu.demo.bean.UserInfo;
import com.lhhu.demo.mapper.HandlersMapper;
import com.lhhu.demo.mapper.LogMapper;
import com.lhhu.demo.mapper.UserMapper;
import com.lhhu.demo.utils.JavaWebToken;
import org.apache.ibatis.annotations.Mapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther 虎
 * @Data 2021/4/9 14:30
 * @Version 1.0
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private HandlersMapper handlersMapper;
    @Autowired
    private UserMapper userMapper;

    @Pointcut("@annotation(com.lhhu.demo.config.LogAnnotation)")
    private void logPointCut(){}

    /**
     * 后置通知
     * @param joinPoint
     */
    @AfterReturning(value = "logPointCut()", returning = "keys")
    public void after(JoinPoint joinPoint,Object keys){

        HttpServletRequest requests = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Logs logs = new Logs();
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        // 从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取切入点所在的模块，行为
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        logs.setModules(logAnnotation.module());
        logs.setTypes(logAnnotation.action());
        //时间，url,ip,返回值
        java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logs.setTimes(dateFormat.format(date));
        logs.setUrl(request.getRequestURI());
        logs.setIp(request.getRemoteAddr());
        logs.setArgs2(JSON.toJSONString(keys));
        // 请求的参数
        Map<String, String> rtnMap = converMap(request.getParameterMap());


        String tokens = requests.getHeader("Authorization");
        if(tokens!=null){
            try{
                Map<String,Object> s = JavaWebToken.parserJavaWebToken(tokens);
                if(s!=null){
                    String openid =  s.toString().substring(8,s.toString().length()-1);
                    UserInfo userInfo = userMapper.selectUserByOpenid(openid).get(0);
                    if(userInfo!=null){
                        logs.setNumbers(openid);
                        logs.setOperator(userInfo.getNickName());
                        // 将参数所在的数组转换成json
                        logs.setArgs1(JSON.toJSONString(rtnMap));

                        logMapper.addOneLog(logs);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            try{
                logs.setNumbers(rtnMap.get("codes"));
                if(logs.getNumbers()!=null){
                    HandlersMessage handlersMessage = handlersMapper.getOneHandlersMessageByCodes(logs.getNumbers());
                    logs.setOperator(handlersMessage.getUsername());
                }else {
                    HandlersMessage handlersMessage = handlersMapper.getOneHandlersMessageByCodes(keys.toString().substring(keys.toString().length()-37,keys.toString().length()-1));
                    logs.setNumbers(keys.toString().substring(keys.toString().length()-37,keys.toString().length()-1));
                    logs.setOperator(handlersMessage.getUsername());
                }
                rtnMap.remove("codes");
                rtnMap.remove("bookUrl");
                // 将参数所在的数组转换成json
                logs.setArgs1(JSON.toJSONString(rtnMap));

                logMapper.addOneLog(logs);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }
}
